package util;

import com.formdev.flatlaf.FlatLightLaf;

import javax.swing.*;
import java.awt.*;
import java.util.List;

/**
 * 组件测试的工具类，用于测试组件功能
 */
public class SwingTestUtils {
	public static int WIDTH = 500;
	public static int HEIGHT = 400;
	public static LayoutManager LAYOUT_MANAGER = new FlowLayout();
	private static JFrame frame;

	public static void loadSkin() {
		// FlatDarkLaf.setup();
		FlatLightLaf.setup();
	}

	public static void test(Component component) {
		test(List.of(component), true);
	}

	public static void test(Component component, LayoutManager layoutManager) {
		LAYOUT_MANAGER = layoutManager;
		test(List.of(component), true);
	}

	/**
	 * 测试重写后的paint()相关的方法，设置组件首选项大小为窗口大小
	 */
	public static void testPaintMethod(Component component, int width, int height) {
		WIDTH = width;
		HEIGHT = height;
		testPaintMethod(component);
	}

	/**
	 * 测试重写后的paint()相关的方法，为传入组件设置好大小
	 */
	public static void testPaintMethod(Component component) {
		component.setPreferredSize(new Dimension(WIDTH, HEIGHT));
		test(List.of(component), false);
	}

	public static void test(Component component1, Component component2) {
		test(List.of(component1, component2), true);
	}

	public static void test(Component component1, Component component2, Component component3) {
		test(List.of(component1, component2, component3), true);
	}

	public static void test(Component ...components) {
		test(List.of(components), true);
	}

	public static void test(List<Component> components, boolean isShowGap) {
		// 这里加了个检测，检测当前线程是否是事件分发线程
		if (SwingUtilities.isEventDispatchThread()) {
			invoke(components, isShowGap);
		} else {
			EventQueue.invokeLater(() -> invoke(components, isShowGap));
		}
	}

	public static void setSize(int width, int height) {
		WIDTH = width;
		HEIGHT = height;
	}

	public static void setTimerTimingSource() {
	}

	public static JFrame getFrame() {
		if (frame == null) {
			frame = new JFrame("测试组件");
			frame.setLayout(new BorderLayout());
			frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
			// 设置窗口居中
			Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
			frame.setLocation((screenSize.width - WIDTH) / 2, (screenSize.height - HEIGHT) / 2);
			// 设置内容窗格
			Container contentPane = frame.getContentPane();
			contentPane.setPreferredSize(new Dimension(WIDTH, HEIGHT));
		}
		return frame;
	}

	/**
	 * 最后执行操作
	 * @param components 组件列表
	 * @param isShowGap 是否显示间距
	 */
	private static void invoke(List<Component> components, boolean isShowGap) {
		Container contentPane = getFrame().getContentPane();

		if (isShowGap)
			contentPane.setLayout(LAYOUT_MANAGER);
		else
			contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));

		components.forEach(contentPane::add);

		frame.pack();
		frame.setVisible(true);
	}
}
